﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mesoBoard.Data.Repositories
{
    public class PluginsRepository : IPluginsRepository
    {
        private mbEntities db;

        public PluginsRepository(mbEntities mbDataContext)
        {
            this.db = mbDataContext;
        }

        public IEnumerable<Plugin> GetPlugins()
        {
            return db.Plugins.AsEnumerable();
        }

        public Plugin GetPlugin(int pluginID)
        {
            return db.Plugins.FirstOrDefault(x => x.PluginID == pluginID);
        }

        public Plugin GetPlugin(string pluginName)
        {
            return db.Plugins.FirstOrDefault(x => x.Name == pluginName);
        }

        public void UpdatePlugin(Plugin plugin)
        {
            if (plugin.EntityKey == null)
                plugin.EntityKey = ((Attachment)db.GetObjectByKey(new System.Data.EntityKey("mbEntities.Plugins", "PluginID", plugin.PluginID))).EntityKey;

            db.Plugins.ApplyCurrentValues(plugin);
            db.SaveChanges();
        }

        public void CreatePlugin(Plugin plugin)
        {
            db.Plugins.AddObject(plugin);
            db.SaveChanges();
        }

        public void DeletePlugin(int pluginID)
        {
            db.Plugins.DeleteObject(db.Plugins.FirstOrDefault(x => x.PluginID == pluginID));
            db.SaveChanges();
        }
    }
}
